<template>
  <view class="goods tn-safe-area-inset-bottom">
    <tn-navbar z-index="2" index-url="/pages/index" fixed :bottom-shadow="false">商品详情</tn-navbar>
    <view class="goods-swiper">
      <!-- 轮播 -->
      <tn-swiper :data="swiperData" indicator-mode="round" :height="windowWidth + 'px'" radius="0"></tn-swiper>
    </view>
    <view class="goods-content">
      <view class="goods-name">{{ purchaseGoods.goodsName }}</view>

      <view class="goods-price"><span>￥</span>{{
        purchaseGoods.price ? formatPrice(purchaseGoods.price, 2) : "0.00"
      }}</view>
      <view class="goods-desc tn-color-main">{{
        purchaseGoods.goodsDesc
      }}</view>
    </view>

    <view class="goods-intro">
      <mp-html :content="purchaseGoods.goodsIntro"></mp-html>
    </view>
    <view class="goods-tool tn-safe-area-inset-bottom">
      <view class="goods-tool-content tn-flex-row">
        <tn-button class="item-add-cart" v-if="cartShow" :disabled="cartDisable" @click="addCart()">
          {{ cartBtnText }}
        </tn-button>
        <tn-button class="item-buy" :disabled="disable" @click="buy()">{{ btnValue
        }}<tn-count-down ref="countDownRef" v-show="countDownShow" separator-type="cn" :autoplay="false"
            @change="countDownChange" @end="endCountDown" :time="countDownTime"
            separator-color="#fff"></tn-count-down></tn-button>
      </view>
    </view>
    <view class="white-block"> </view>

    <tn-toast ref="toast"></tn-toast>
    <tn-tips ref="defaultTips" :top="customNavbar.height + 'px'"></tn-tips>
  </view>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import useSystemInfo from "@/tuniao-ui/libs/hooks/useSystemInfo";
import TnNavbar from "@/tuniao-ui/components/tn-navbar/src/Navbar.vue";
import TnSwiper from "@/tuniao-ui/components/tn-swiper/src/Swiper.vue";
import TnTag from "@/tuniao-ui/components/tn-tag/src/Tag.vue";
import TnIcon from "@/tuniao-ui/components/tn-icon/src/Icon.vue";
import TnButton from "@/tuniao-ui/components/tn-button/src/Button.vue";
import TnPopup from "@/tuniao-ui/components/tn-popup/src/Popup.vue";
import TnToast from "@/tuniao-ui/components/tn-toast/src/Toast.vue";
import TnTips from "@/tuniao-ui/components/tn-tips/src/Tips.vue";
import TnCountDown from "@/tuniao-ui/components/tn-count-down/src/CountDown.vue";
import mpHtml from "mp-html/dist/uni-app/components/mp-html/mp-html.vue";
import { SwiperData } from "@/tuniao-ui/types";
import { formatPrice } from "@/tuniao-ui/utils";
import {
  findRushPurchaseDetail,
  buyRushPurchaseDetail,
} from "@/api/purchaseDetail";
import {
  isHaveRushPurchaseCart,
  addRushPurchaseCart,
} from "@/api/purchaseCart";
import { getPrivilegeInfo } from "@/api/purchase";
import { PurchaseGoods } from "./lib/PurchaseGoods";
import { ResultEnum } from "@/enums/httpEnum";
import { useUserStore } from "@/tuniao-ui/store/user";

const purchaseDetailId = ref(0);

const disable = ref(false);
const btnValue = ref("加载中");

//const nowTime = Math.floor(new Date().getTime() / 1000);
const nowTime = ref(0);
const countDownTime = ref(0); // 倒计时组件时间
const earlyEntryTime = ref(0); // 提前入场时间
const countDownRef = ref<InstanceType<typeof TnCountDown>>();
const countDownShow = ref(false);
const cartShow = ref(false);
const cartBtnText = ref("加入购物车");
const cartDisable = ref(false);

const defaultTips = ref<InstanceType<typeof TnTips>>();
const toast = ref<InstanceType<typeof TnToast>>();

const purchaseGoods: PurchaseGoods = reactive({
  id: 0,
  goodsId: 0,
  goodsName: "",
  goodsDesc: "",
  price: 0.0, // 活动商品销售价
  originalPrice: 0.0, // 活动商品原价
  goodsSkuSn: "", //货号
  status: 0,
  goodsImgs: [], // 商品图片
  goodsIntro: "",
  startTime: "",
  endTime: "",
  createTime: "",
});

// 轮播图数据
const swiperData = ref<SwiperData[]>([]);
const { updateSystemInfo, systemInfo, customNavbar } = useSystemInfo();
updateSystemInfo();
const windowWidth = systemInfo.value.windowWidth;

const userStore = useUserStore();

function buy() {
  console.log("点击购买");
  let nowTime = Math.floor(new Date().getTime() / 1000) + earlyEntryTime.value;
  
  if (nowTime > Number(purchaseGoods.startTime)) {
    buyRushPurchaseDetail({
      rushPurchaseDetailId: purchaseDetailId.value,
    }).then((res: any) => {
      if (res.code == ResultEnum.SUCCESS) {
        if (res.result == "success") {
          //console.log("成功");
          toast.value?.show({
            title: "抢购成功",
            icon: "success",
          });
          disable.value = true;
          btnValue.value = "已售罄";
        } else {
          toast.value?.show({
            title: "抢购失败:" + res.result,
          });
        }
      } else {
        toast.value?.show({
          title: res.message,
        });
      }
    });
  } else {
    console.log("活动未开始");
  }
}

function addCart() {
  let params = {
    goodsName: purchaseGoods.goodsName,
    price: purchaseGoods.price,
    goodsImg: purchaseGoods.goodsImgs[0],
    rushPurchaseDetailId: purchaseDetailId.value,
    memberId: userStore.getId,
  };
  addRushPurchaseCart(params).then((res: any) => {
    if (res.code == ResultEnum.SUCCESS) {
      //console.log("成功");
      toast.value?.show({
        title: "加入购物车成功",
        icon: "success",
      });
      cartDisable.value = true;
      cartBtnText.value = "已售罄";
    } else {
      toast.value?.show({
        title: "加入购物车失败:" + res.message,
        icon: "close",
      });
    }
  });
}

function countDownChange(e) {

  // 如果可以抢了
  if (e <= earlyEntryTime.value) {
    countDownShow.value = false;
    btnValue.value = "立即抢购";
  } else {
    btnValue.value = "还剩";
  }
}

function endCountDown() {
  countDownShow.value = false;
  btnValue.value = "立即抢购";
}

onMounted(() => {
  let timer = setTimeout(() => {
    let gradeId = userStore.getUserInfo.gradeId;
    //2是提前抢会员 3是提前抢+无限抢会员   暂时用id控制
    if (gradeId == 2) {
      defaultTips.value?.show({
        duration: 5000,
        msg: "尊贵的优先会员，已为您开通提前抢购，抢购时间已提前30秒。",
      });
    }
    if (gradeId == 3) {
      defaultTips.value?.show({
        duration: 5000,
        msg: "尊贵的尊享会员，已为您开通提前抢购和不限抢购，抢购时间已提前30秒。",
      });
    }
    if (gradeId == 4) {
      defaultTips.value?.show({
        duration: 5000,
        msg: "尊贵的团长，已为您开通购物车功能。",
      });
    }
    if (gradeId == 5) {
      defaultTips.value?.show({
        duration: 5000,
        msg: "尊贵的尊享会员，已为您开通购物车功能。",
      });
    }
  }, 1000);
});

onLoad((options: any) => {
  purchaseDetailId.value = options.purchaseDetailId;

  findRushPurchaseDetail({ id: purchaseDetailId.value }).then((res: any) => {
    const goodsInfo = res.result;
    Object.assign(purchaseGoods, goodsInfo);
    for (const img of purchaseGoods.goodsImgs) {
      swiperData.value.push({
        image: img,
      });
    }

    if (goodsInfo.status != 0) {
      disable.value = true;
      btnValue.value = "已售罄";
      return;
    }

    if (nowTime > goodsInfo.endTime) {
      disable.value = true;
      cartDisable.value = true;
      btnValue.value = "已结束";
      return;
    }

    nowTime.value = Math.floor(new Date().getTime() / 1000);
    // 未开始  开始倒计时
    if (nowTime.value < goodsInfo.startTime) {
      countDownTime.value = Number(goodsInfo.startTime) - nowTime.value;

      //countDownTime.value = 5;
      // btnValue.value = "还剩";
      countDownShow.value = true;
      countDownRef.value?.setTime(countDownTime.value);
      countDownRef.value?.start();

      // 提前抢购和购物车权限 抢购开始前拥有
      getPrivilegeInfo({id: goodsInfo.rushPurchaseId}).then((result) => {
        console.log(result, "特权信息");
        if (result.code == ResultEnum.SUCCESS) {
          if (result.result.earlyEntryTime) {
            earlyEntryTime.value = result.result.earlyEntryTime;
          }
          if (result.result.isHaveCart) {
            cartShow.value = result.result.isHaveCart == 1 ? true : false;
          }
        }
      });
    } else {
      btnValue.value = "立即抢购";
    }
  });

  getPrivilegeInfo
  //earlyEntryTime

  // 判断是否加入
  isHaveRushPurchaseCart({
    rushPurchaseDetailId: purchaseDetailId.value,
  }).then((res: any) => {
    if (res.code == ResultEnum.SUCCESS) {
      // 如果已存在
      if (res.result) {
        cartDisable.value = true;
        cartBtnText.value = "已售罄";
      }
    }
  });
});
</script>

<style lang="scss" scoped>
.goods-content {
  padding: 30rpx 20rpx 10rpx 20rpx;
  background-color: #fff;

  .goods-name {
    font-size: 30rpx;
    margin-top: 20rpx;
  }

  .goods-desc {
    margin-top: 20rpx;
    font-size: 28rpx;
    // color: #CCA220;
  }

  .goods-price {
    margin-top: 20rpx;
    font-weight: bold;
    font-size: 38rpx;

    span {
      font-size: 30rpx;
    }
  }
}

.goods-tool {
  padding: 0 20rpx;
  width: 100%;
  position: fixed;
  bottom: 0;
  background-color: #fff;
  height: 100rpx;

  &-content {
    height: 100rpx;
    display: flex;
    justify-content: center;
    align-items: center;

    .item-add-cart {
      width: 300rpx;
      height: 80rpx;
      margin-right: 10rpx;
    }

    .item-buy {
      width: 100%;
      height: 80rpx;
    }
  }
}

.goods-intro {
  margin-top: 30rpx;
  padding: 20rpx;
  background-color: #fff;
}

.white-block {
  width: 100%;
  height: 120rpx;
}
</style>
